package org.jeecg.modules.arc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.arc.entity.ArcAdjustedConfigs;
import org.jeecg.modules.arc.mapper.ArcAdjustedConfigsMapper;
import org.jeecg.modules.arc.service.IArcAdjustedConfigsService;
import org.jeecg.modules.arc.vo.ArcAdjustedConfigVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Description: 增减水量策略
 * @Author: jeecg-boot
 * @Date:   2022-02-10
 * @Version: V1.0
 */
@Service
public class ArcAdjustedConfigsServiceImpl extends ServiceImpl<ArcAdjustedConfigsMapper, ArcAdjustedConfigs> implements IArcAdjustedConfigsService {

    @Resource
    private ArcAdjustedConfigsMapper configsMapper;

    @Override
    public BigDecimal measureAdjustAmount(String cusId, BigDecimal amount) {
        ArcAdjustedConfigVO adjustedConfigVO = queryAdjustConfig(cusId);
        if(null == adjustedConfigVO){
            //不存在直接返回增减0
            return  new BigDecimal(0.0);
        }

        //校验是否过期或开始
        if(adjustedConfigVO.getBeginTime().getTime() > DateUtils.getDate().getTime()){
            //还没开始
            return  new BigDecimal(0.0);
        }else if(null != adjustedConfigVO.getEndTime() && DateUtils.getDate().getTime() >  adjustedConfigVO.getBeginTime().getTime()){
            //已结束 当前时间大于结束时间
            return new BigDecimal(0.0);
        }

        if("1".equals(adjustedConfigVO.getWaterConfigsType())){
            //固定量
            BigDecimal subtract = amount.subtract(adjustedConfigVO.getValue());
            if(subtract.doubleValue()>=0){
                return adjustedConfigVO.getValue();
            }else{
                return amount;
            }

        }else if("2".equals(adjustedConfigVO.getWaterConfigsType())){
            //比例
            BigDecimal bigDecimal = amount.multiply(adjustedConfigVO.getValue())
                    .setScale(2, BigDecimal.ROUND_HALF_UP);
            if(bigDecimal.doubleValue()>=0){
                return bigDecimal;
            }else{
                return amount;
            }
        }
        return  new BigDecimal(0.0);
    }

    @Override
    public ArcAdjustedConfigVO queryAdjustConfig(String cusId) {
        List<ArcAdjustedConfigVO> adjustedConfigVOS = configsMapper.queryAdjustConfig(cusId);
        if(null != adjustedConfigVOS && adjustedConfigVOS.size()>0){
            return adjustedConfigVOS.get(0);
        }
        return null;
    }
}
